<template>
  <a-spin :spinning="spinning" tip="加载中...">
    <a-card :bordered="false">
      <h3 style="margin-bottom: 20px;">路径转H5链接工具</h3>
      <a-tabs :activeKey="activeTab" @change="tabChange">
        <a-tab-pane :key="1" tab="微商城"> </a-tab-pane>
        <a-tab-pane :key="2" tab="BOX" force-render> </a-tab-pane>
      </a-tabs>
      <a-form-model
        ref="rulesForm"
        :model="form"
        :rules="activeTab == 2 ? rules2 : rules"
        :labelCol="{ lg: { span: 4 }, sm: { span: 6 } }"
        :wrapperCol="{ lg: { span: 18 }, sm: { span: 18 } }"
        @keyup.enter.native="handleSubmit"
      >
        <a-form-model-item label="小程序" prop="brandId">
          <a-select v-model="form.brandId" placeholder="请选择" show-search :filter-option="filterOption">
            <template v-if="activeTab == 1">
              <a-select-option :value="item.weid" v-for="item in brandList" :key="item.weid"> {{ item.name }}</a-select-option>
            </template>
            <template v-if="activeTab == 2">
              <a-select-option :value="1">BOX</a-select-option>
            </template>
          </a-select>
        </a-form-model-item>
        <!-- <a-form-model-item label="活动标识" prop="type">
          <a-input v-model.trim="form.type" placeholder="请输入英文字母" allowClear />
        </a-form-model-item> -->
        <a-form-model-item label="路径" prop="path">
          <a-input v-model.trim="form.path" placeholder="请输入以/开头的小程序路径" allowClear v-if="activeTab == 1" />
          <a-input v-model.trim="form.path" placeholder="请输入小程序路径，比如pages/xxxx/xxx" allowClear v-if="activeTab == 2" />
        </a-form-model-item>
        <a-form-model-item :wrapperCol="{ span: 24 }" style="text-align: center;margin-top: 20px;">
          <a-button @click="handleSubmit" type="primary">转换</a-button>
          <a-button style="margin-left: 10px;" @click="handleResetFields">重置</a-button>
        </a-form-model-item>
      </a-form-model>
      <a-card v-if="h5Link" :bordered="false" style="background: #F6F3F3;max-width: 800px;margin: 0 auto;">
        <a-form-item label="H5链接">
          <div style="word-break: break-all;">{{ h5Link }} <a style="text-decoration: underline;" :data-clipboard-text="h5Link" @click="copy('h5Link')" id="h5Link">复制</a></div>
          <div style="margin-top: 10px;width: 150px;" v-if="qrcodeUrl">
            <img :src="qrcodeUrl" alt="" class="qrcode" />
            <a-button @click="downloadImage(qrcodeUrl, type)" style="display: block;margin: 5px auto 0;" type="primary" v-if="activeTab == 1">下载太阳码</a-button>
            <a-button @click="downloadImage(qrcodeUrl, '小程序码')" style="display: block;margin: 5px auto 0;" type="primary" v-if="activeTab == 2">下载太阳码</a-button>
          </div>
        </a-form-item>
      </a-card>
    </a-card>
  </a-spin>
</template>
<script>
import { operationChain, createScene } from '@/api/marketingCenter/luckyDraw'
import { contentPromote } from '@/api/micromall/communityContent'
import { brandList } from '../components/brandList'
import Clipboard from 'clipboard'
import moment from 'moment'

export default {
  components: {},
  data() {
    return {
      activeTab: 1,
      type: '',
      moment,
      qrcodeUrl: '',
      h5Link: '',
      brandList,
      spinning: false,
      form: {
        brandId: '',
        path: ''
        // type: ''
      },
      rules: {
        path: [
          { required: true, message: '请输入', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              const reg = /^\/\S*$/
              const reg2 = /[\u4e00-\u9fa5]/g
              if (!value) {
                callback()
              } else {
                if (reg.test(value) && !reg2.test(value)) {
                  callback()
                } else {
                  return callback(new Error('请以/开头且不能含空格和汉字'))
                }
              }
            },
            trigger: 'blur'
          }
        ],
        brandId: [{ required: true, message: '请选择', trigger: 'change' }]
      },
      rules2: {
        path: [
          { required: true, message: '请输入', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              const reg = /^\/\S*$/
              const reg2 = /[\u4e00-\u9fa5]/g
              if (!value) {
                callback()
              } else {
                if (!reg2.test(value)) {
                  callback()
                } else {
                  return callback(new Error('请以英文开头且不能含空格和汉字'))
                }
              }
            },
            trigger: 'blur'
          }
        ],
        brandId: [{ required: true, message: '请选择', trigger: 'change' }]
      }
    }
  },
  watch: {},
  activated() {},
  created() {},
  computed: {},
  mounted() {},
  methods: {
    // 重置
    handleResetFields() {
      this.$refs.rulesForm.resetFields()
      this.h5Link = ''
      this.qrcodeUrl = ''
      this.type = ''
    },

    // 复制
    copy(id) {
      let tag = `#${id}`
      var clipboard = new Clipboard(tag)
      clipboard.on('success', e => {
        console.log(e)
        this.$message.success('复制成功')
        // 释放内存
        clipboard.destroy()
      })
      clipboard.on('error', e => {
        console.log(e)
        // 不支持复制
        console.log('复制失败')
        // 释放内存
        clipboard.destroy()
      })
    },

    // 转换
    handleSubmit() {
      this.$refs.rulesForm.validate(valid => {
        if (valid) {
          const { brandId, path } = this.form
          const data = {
            jumpPath: path
          }
          if (this.activeTab == 1) {
            this.getWeixinQrcode(path, brandId)
            this.spinning = true
            operationChain(data)
              .then(res => {
                this.spinning = false
                if (res.code === 200) {
                  this.$message.success('转换成功！')
                  this.type = res.data
                  this.h5Link = `https://jic.jnby.com/schain1/index.html?brandId=${brandId}&type=${res.data}&path=${path}`
                } else {
                  this.$message.error(res.msg || res.message)
                }
              })
              .catch(err => {
                this.spinning = false
              })
          }
          if (this.activeTab == 2) {
            this.spinning = true
            this.boxCreateScene()
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    getWeixinQrcode(path, brandId) {
      console.log(path.indexOf('?'))
      const data = {
        url: path,
        weid: brandId
      }
      contentPromote(data).then(res => {
        if (res.code === 200) {
          this.qrcodeUrl = res.data
        } else {
          this.$message.error(res.msg || res.message)
        }
      })
    },

    downloadImage(imgsrc, name) {
      var image = new Image()
      image.setAttribute('crossOrigin', 'anonymous')
      image.onload = function() {
        var canvas = document.createElement('canvas')
        canvas.width = image.width
        canvas.height = image.height
        var context = canvas.getContext('2d')
        context.drawImage(image, 0, 0, image.width, image.height)
        var url = canvas.toDataURL('image/jpeg')
        var a = document.createElement('a')
        var event = new MouseEvent('click')
        a.download = name || 'photo'
        a.href = url
        a.dispatchEvent(event)
      }
      image.src = imgsrc
    },
    filterOption(input, option) {
      return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
    },
    // tab切换
    tabChange(key) {
      this.activeTab = key
      this.handleResetFields()
      if (key == 2) {
        this.form.brandId = 1
      }
    },
    boxCreateScene() {
      console.log(1223)
      const { path } = this.form
      let params = {
        requestData: {
          code: 31,
          ifCreateQrCode: true,
          params: {
            path: path
          }
        }
      }
      createScene(params)
        .then(res => {
          this.spinning = false
          if (res.code == 0) {
            this.$message.success('转换成功！')
            this.qrcodeUrl = res.data.codeUrl
            this.h5Link =
              process.env.NODE_ENV === 'production' ? `https://bzhz.jnbygroup.com/mobile/commonlink.html?path=${path}` : `https://testbzhz.jnbygroup.com/mobile/commonlink.html?path=${path}`
          } else {
            this.$message.error(res.msg || res.message)
          }
        })
        .catch(err => {
          this.spinning = false
        })
    }
  }
}
</script>
<style lang="less" scoped>
.qrcode {
  width: 150px;
  height: 150px;
}
</style>

